<template>
  <div class="devtools-container">
    <div class="main-layout">
      <!-- 左侧请求列表 -->
      <div class="requests-container" :class="{ 'with-detail': selectedRequest }">
        <div class="panel-header">
          <h2>解密面板</h2>
          <div class="controls">
            <button @click="clearRequests" class="clear-btn">清空</button>
          </div>
        </div>
        <div v-if="requests.length === 0" class="empty-state">
          <p>暂无网络请求数据</p>
          <p class="hint">在页面上产生网络请求或在 Network 面板中右键点击请求，选择"发送到 Crypt 面板"</p>
        </div>
        <div v-else class="requests-list">
          <div
            v-for="request in requests"
            :key="request.requestId || request.startedDateTime"
            class="request-item"
            :class="{ active: selectedRequest && getRequestId(selectedRequest) === getRequestId(request) }"
            @click="toggleRequest(request)"
          >
            <div class="request-summary">
              <span :class="['method', request.request.method]">{{ request.request.method }}</span>
              <span class="url">{{ truncateUrl(getRequestUrl(request), 50) }}</span>
              <span v-if="request.response" class="status" :class="getStatusClass(request.response.status)">
                {{ request.response.status }}
              </span>
            </div>
            <div class="request-time">
              {{ formatTime(request.time || 0) }}
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧详情面板 -->
      <div v-if="selectedRequest" class="detail-panel">
        <div class="panel-header">
          <h3>请求详情</h3>
          <button class="close-btn" @click="closeDetail">×</button>
        </div>
        <div class="panel-content">
          <!-- 使用 Element Plus 的 Tabs 组件 -->
          <el-tabs v-model="activeTab">
            <!-- 基本信息 -->
            <el-tab-pane label="Info" name="info">
              <div class="request-info">
                <div class="info-item">
                  <label>URL:</label>
                  <div class="value">{{ getRequestUrl(selectedRequest) }}</div>
                </div>
                <div class="info-item">
                  <label>Method:</label>
                  <div class="value">{{ selectedRequest.request.method }}</div>
                </div>
                <div v-if="selectedRequest.response" class="info-item">
                  <label>Status:</label>
                  <div class="value">{{ selectedRequest.response.status }} {{ selectedRequest.response.statusText }}</div>
                </div>
                <div class="info-item">
                  <label>时间:</label>
                  <div class="value">{{ formatTime(selectedRequest.time || 0) }}</div>
                </div>
              </div>
            </el-tab-pane>

            <!-- Headers -->
            <el-tab-pane label="Headers" name="headers">
              <h4>Request Headers</h4>
              <div class="headers-list">
                <div
                  v-for="header in selectedRequest.request.headers"
                  :key="header.name"
                  class="header-item"
                >
                  <span class="header-name">{{ header.name }}:</span>
                  <span class="header-value">{{ header.value }}</span>
                </div>
              </div>

              <h4>Response Headers</h4>
              <div class="headers-list">
                <div
                  v-for="header in (selectedRequest.response?.headers || [])"
                  :key="header.name"
                  class="header-item"
                >
                  <span class="header-name">{{ header.name }}:</span>
                  <span class="header-value">{{ header.value }}</span>
                </div>
              </div>
            </el-tab-pane>

            <!-- Payload -->
            <el-tab-pane label="Payload" name="payload">
              <h4>Request Payload</h4>
              <pre v-if="selectedRequest.request.postData">{{ selectedRequest.request.postData.text }}</pre>
              <div v-else>无请求体</div>
            </el-tab-pane>

            <!-- Response -->
            <el-tab-pane label="Response" name="response">
              <h4>Response</h4>
              <pre v-if="selectedRequest.response?.content?.text">{{ selectedRequest.response.content.text }}</pre>
              <div v-else>无响应内容</div>
            </el-tab-pane>

            <!-- Crypt 解析 -->
            <el-tab-pane label="Crypt" name="crypt">
              <h4>Crypt 解析内容</h4>
              <div class="crypt-controls">
                <el-button type="primary" @click="parseContent" size="small">解析内容</el-button>
              </div>
              <pre v-if="parsedContent">{{ parsedContent }}</pre>
              <div v-else class="empty-parse">
                点击"解析内容"按钮解析响应数据
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </div>
  </div>
</template>


<script>
import { ref, onMounted, onUnmounted } from 'vue'

export default {
  setup() {
    const requests = ref([])
    const selectedRequest = ref(null)
    const activeTab = ref('info')
    const parsedContent = ref('')

    const tabs = [
      { id: 'info', name: 'Info' },
      { id: 'headers', name: 'Headers' },
      { id: 'payload', name: 'Payload' },
      { id: 'response', name: 'Response' },
      { id: 'crypt', name: 'Crypt' }
    ]

    // 消息处理函数
    const handleMessage = (event) => {
      if (event.data.type === 'NETWORK_REQUEST') {
        addRequestToList(event.data.data)
      } else if (event.data.type === 'SELECTED_REQUEST') {
        // 处理从右键菜单发送的请求
        addRequestToList(event.data.data)
        selectRequest(event.data.data)
      }
    }

    // 添加请求到列表
    const addRequestToList = (request) => {
      // 检查是否已存在
      const existingIndex = requests.value.findIndex(req =>
        getRequestId(req) === getRequestId(request)
      )

      if (existingIndex === -1) {
        requests.value.push(request)
      } else {
        // 更新已存在的请求
        requests.value[existingIndex] = request
      }
    }

    // 获取请求唯一标识
    const getRequestId = (request) => {
      return request.requestId || request.startedDateTime || request.request.url
    }

    // 获取请求URL
    const getRequestUrl = (request) => {
      return request.request?.url || ''
    }

    // 监听来自 devtools 的消息
    onMounted(() => {
      window.addEventListener('message', handleMessage)
    })

    // 清理事件监听器
    onUnmounted(() => {
      window.removeEventListener('message', handleMessage)
    })

    // 切换请求选择状态
    const toggleRequest = (request) => {
      if (selectedRequest.value && getRequestId(selectedRequest.value) === getRequestId(request)) {
        selectedRequest.value = null
        activeTab.value = 'info'
      } else {
        selectRequest(request)
      }
    }

    // 选择请求
    const selectRequest = (request) => {
      selectedRequest.value = request
      activeTab.value = 'info'
      parsedContent.value = ''
    }

    // 关闭详情面板
    const closeDetail = () => {
      selectedRequest.value = null
      activeTab.value = 'info'
      parsedContent.value = ''
    }

    // 清空请求列表
    const clearRequests = () => {
      requests.value = []
      selectedRequest.value = null
      activeTab.value = 'info'
      parsedContent.value = ''
    }

    const getStatusClass = (status) => {
      if (!status) return 'info'
      if (status >= 200 && status < 300) return 'success'
      if (status >= 400) return 'error'
      return 'info'
    }

    // 截断URL显示
    const truncateUrl = (url, maxLength) => {
      if (!url) return ''
      if (url.length <= maxLength) return url
      return url.substring(0, maxLength) + '...'
    }

    // 格式化时间
    const formatTime = (time) => {
      if (!time) return '0ms'
      if (time < 1000) return `${Math.round(time)}ms`
      return `${(time / 1000).toFixed(2)}s`
    }

    // 解析内容
    const parseContent = () => {
      if (!selectedRequest.value || !selectedRequest.value.response) {
        parsedContent.value = '无响应内容可解析'
        return
      }

      const response = selectedRequest.value.response
      if (!response.content || !response.content.text) {
        parsedContent.value = '响应内容为空'
        return
      }

      try {
        // 这里实现你的解密/解析逻辑
        // 示例：尝试解析 JSON
        const text = response.content.text
        let parsed

        // 如果是 JSON 格式
        if (response.content.mimeType && response.content.mimeType.includes('json')) {
          parsed = JSON.parse(text)
        }
        // 如果是加密内容，你需要在这里实现解密逻辑
        else if (text.startsWith('{') || text.startsWith('[')) {
          parsed = JSON.parse(text)
        }
        else {
          // 自定义解密逻辑
          parsed = decryptContent(text)
        }

        parsedContent.value = JSON.stringify(parsed, null, 2)
      } catch (e) {
        parsedContent.value = `解析失败: ${e.message}\n\n原始内容:\n${response.content.text}`
      }
    }

    // 示例解密函数（你需要根据实际情况实现）
    const decryptContent = (text) => {
      // 这里实现你的解密逻辑
      // 目前只是返回原文本
      return {
        original: text,
        message: "请在此处实现你的解密逻辑"
      }
    }

    return {
      requests,
      selectedRequest,
      activeTab,
      tabs,
      parsedContent,
      toggleRequest,
      closeDetail,
      clearRequests,
      getStatusClass,
      truncateUrl,
      formatTime,
      getRequestUrl,
      getRequestId,
      parseContent
    }
  }
}
</script>

<style>
body {
  padding: 0;
  margin: 0;
}
</style>

<style scoped>
.devtools-container {
  padding: 0;
  font-family: Arial, sans-serif;
  height: 100vh;
  overflow: hidden;
}

.main-layout {
  display: flex;
  height: 100%;
}

.requests-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  border-right: 1px solid #ddd;
}

.requests-container.with-detail {
  flex: 0 0 50%;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #eee;
}

.panel-header h2 {
  margin: 0;
  font-size: 16px;
}

.controls {
  display: flex;
  gap: 5px;
}

.clear-btn {
  background: #f5f5f5;
  border: 1px solid #ddd;
  padding: 4px 8px;
  border-radius: 3px;
  cursor: pointer;
  font-size: 12px;
}

.clear-btn:hover {
  background: #e0e0e0;
}

.detail-panel {
  flex: 0 0 50%;
  display: flex;
  flex-direction: column;
  border-left: 1px solid #ddd;
  background-color: #fff;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  padding: 0;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.panel-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.tabs {
  display: flex;
  border-bottom: 1px solid #eee;
  background: #f5f5f5;
}

.tab {
  padding: 8px 16px;
  border: none;
  background: none;
  cursor: pointer;
  border-right: 1px solid #ddd;
  font-size: 13px;
}

.tab.active {
  background: #fff;
  font-weight: bold;
}

.tab-content {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.tab-pane {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.tab-pane h4 {
  margin: 10px 0 5px 0;
  font-size: 14px;
}

.request-info {
  margin-bottom: 20px;
}

.info-item {
  margin-bottom: 10px;
  display: flex;
}

.info-item label {
  font-weight: bold;
  width: 80px;
  flex-shrink: 0;
}

.info-item .value {
  flex: 1;
  word-break: break-all;
}

.headers-list {
  margin-bottom: 20px;
}

.header-item {
  display: flex;
  margin-bottom: 5px;
  font-size: 12px;
}

.header-name {
  font-weight: bold;
  width: 200px;
  flex-shrink: 0;
}

.header-value {
  flex: 1;
  word-break: break-all;
}

pre {
  white-space: pre-wrap;
  word-break: break-all;
  margin: 0 0 10px 0;
  font-size: 12px;
  background: #f8f9fa;
  padding: 10px;
  border-radius: 4px;
  max-height: 300px;
  overflow-y: auto;
}

.crypt-controls {
  margin-bottom: 10px;
}

.parse-btn {
  background: #1a73e8;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.parse-btn:hover {
  background: #0d62c9;
}

.empty-parse {
  color: #666;
  font-style: italic;
  text-align: center;
  padding: 20px;
}

.request-item {
  padding: 8px;
  border: 1px solid #ddd;
  margin-bottom: 5px;
  cursor: pointer;
  border-radius: 4px;
}

.request-item:hover {
  background-color: #f5f5f5;
}

.request-item.active {
  background-color: #e3f2fd;
  border-color: #2196f3;
}

.request-summary {
  display: flex;
  align-items: center;
  gap: 10px;
}

.request-time {
  font-size: 11px;
  color: #666;
  margin-top: 4px;
}

.method {
  font-weight: bold;
  width: 60px;
  flex-shrink: 0;
  font-size: 11px;
}

.method.GET { color: #28a745; }
.method.POST { color: #007bff; }
.method.PUT { color: #ffc107; }
.method.DELETE { color: #dc3545; }

.url {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 12px;
}

.status {
  width: 40px;
  text-align: center;
  padding: 2px 4px;
  border-radius: 3px;
  font-size: 11px;
  flex-shrink: 0;
}

.status.success { background-color: #d4edda; color: #155724; }
.status.error { background-color: #f8d7da; color: #721c24; }
.status.info { background-color: #cce7ff; color: #004085; }

.empty-state {
  text-align: center;
  color: #666;
  padding: 40px 20px;
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.empty-state .hint {
  font-size: 13px;
  color: #999;
  margin-top: 10px;
}

@media (max-width: 768px) {
  .main-layout {
    flex-direction: column;
  }

  .requests-container.with-detail {
    flex: 1;
  }

  .detail-panel {
    flex: 1;
    border-left: none;
    border-top: 1px solid #ddd;
  }
}
</style>
